import { DateTime } from 'luxon'

// d must be a Date object
export function toISOStringWithoutMilliseconds(d) {
  const origin = d.toISOString()
  const parts = origin.split('.')
  return parts.length > 0 ? `${parts[0]}Z` : origin
}

// d1, d2 must be ISO Date string
export function toDateIntervalString(d1, d2, format = { long: 'yyyy.M.d', short: 'M.d' }) {
  const start = d1 ? DateTime.fromISO(d1) : null
  const end = d2 ? DateTime.fromISO(d2) : null
  if (start && end && end.hasSame(start, 'day')) {
    return start.toFormat(format.long)
  } else if (start && end && end.hasSame(start, 'year')) {
    return `${start.toFormat(format.long)} ~ ${end.toFormat(format.short)}`
  } else {
    return (start ? start.toFormat(format.long) : '待定') + (end ? ` ~ ${end.toFormat(format.long)}` : '')
  }
}

// d1, d2 must be ISO Date string, Date object, or null
export function toDateDurationString(d1, d2) {
  if (!d1 || !d2) {
    return ''
  }
  const days = DateTime.fromISO(d2).diff(DateTime.fromISO(d1), 'days').days
  return days > 0 ? `${Math.ceil(days)}天` : ''
}

export function oralizeTime(isoTimeStr) {
  const t = DateTime.fromISO(isoTimeStr)
  if (!t.isValid) {
    return isoTimeStr
  }
  const now = DateTime.now()
  const duration = { days: -1 }
  if (now.hasSame(t, 'day')) {
    const diff = Math.floor(now.diff(t, 'hours').toObject().hours)
    if (diff < 0) {
      return t.toFormat('HH:mm')
    } else if (diff < 1) {
      return '刚刚'
    } else {
      return `${diff}小时前`
    }
  } else if (now.plus(duration).hasSame(t, 'day')) {
    return t.toFormat('昨天 HH:mm')
  } else if (now.hasSame(t, 'year')) {
    return t.toFormat('M-d HH:mm')
  } else {
    return t.toFormat('yyyy-M-d HH:mm')
  }
}

export function isUntilNow(isoTimeStr) {
  return isoTimeStr && isoTimeStr.startsWith?.('9999')
}
